import React, { useState, useEffect } from 'react';
import { Spin, Typography } from 'antd';
import MainLayout from '../../../components/MainLayout';
import PageHeader from './components/PageHeader';
import UserNetworksSection from './components/UserNetworksSection';
import PublicNetworksSection from './components/PublicNetworksSection';
import networkService from '../../../services/network';
import './NetworkHome.css';
import Toast from '../../../components/Toast';

const { Title } = Typography;

const NetworkHome = () => {
  // 状态管理
  const [joinedNetworks, setJoinedNetworks] = useState([]);
  const [managedNetworks, setManagedNetworks] = useState([]);
  const [publicNetworks, setPublicNetworks] = useState([]);
  const [joinedLoading, setJoinedLoading] = useState(true);
  const [managedLoading, setManagedLoading] = useState(false);
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [networkTypeFilter, setNetworkTypeFilter] = useState('all'); 
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 6,
    total: 0
  });
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 加载已加入的网络
  const loadJoinedNetworks = async () => {
    try {
      setJoinedLoading(true);
      const response = await networkService.getUserNetworks('joined');
      if (response.data.code === 200) {
        setJoinedNetworks(response.data.data || []);
      } else {
        showToastMessage(response.data.message || '加载已加入网络失败');
      }
    } catch (error) {
      showToastMessage('加载已加入网络失败');
    } finally {
      setJoinedLoading(false);
    }
  };

  // 加载管理的网络
  const loadManagedNetworks = async () => {
    try {
      setManagedLoading(true);
      const response = await networkService.getUserNetworks('managed');
      if (response.data.code === 200) {
        setManagedNetworks(response.data.data || []);
      } else {
        showToastMessage(response.data.message || '加载管理网络失败');
      }
    } catch (error) {
      showToastMessage('加载管理网络失败');
    } finally {
      setManagedLoading(false);
    }
  };

  // 加载所有用户网络
  const loadAllUserNetworks = async () => {
    await Promise.all([
      loadJoinedNetworks(),
      loadManagedNetworks()
    ]);
  };

  // 搜索公共网络 - 更新函数签名以支持网络类型筛选
  const handleSearch = async (
    keyword = searchKeyword, 
    status = statusFilter, 
    networkType = networkTypeFilter
  ) => {
    try {
      setSearchLoading(true);
      
      // 构建搜索参数
      const params = {
        keyword: keyword,
        status: status === 'all' ? undefined : status,
        current: pagination.current,
        size: pagination.pageSize
      };

      // 处理网络类型筛选
      if (networkType === 'public') {
        params.isPublic = true;
      } else if (networkType === 'private') {
        params.isPublic = false;
      }
      // networkType === 'all' 时不添加 isPublic 参数，显示所有类型
      
      // 移除undefined值
      Object.keys(params).forEach(key => 
        params[key] === undefined && delete params[key]
      );


      const response = await networkService.searchNetworks(params);
      
      if (response.data.code === 200) {
        setPublicNetworks(response.data.data?.records || []);
        setPagination(prev => ({
          ...prev,
          total: response.data.data?.total || 0
        }));
      } else {
        showToastMessage(response.data.message || '搜索网络失败');
      }
    } catch (error) {
      showToastMessage('搜索网络失败');
    } finally {
      setSearchLoading(false);
    }
  };

  // 分页变化处理
  const handlePageChange = (page, pageSize) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize || prev.pageSize
    }));
  };

  // 搜索条件变化处理
  const handleSearchChange = (keyword) => {
    setSearchKeyword(keyword);
  };

  const handleStatusFilterChange = (status) => {
    setStatusFilter(status);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 网络类型筛选变化处理
  const handleNetworkTypeFilterChange = (networkType) => {
    setNetworkTypeFilter(networkType);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理网络加入成功
  const handleNetworkJoined = async (networkId) => {
    // 重新加载用户网络列表
    await loadAllUserNetworks();
    // 可选：从公共网络列表中移除已加入的网络
    setPublicNetworks(prev => prev.filter(network => network.networkId !== networkId));
  };

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  // 初始化数据
  useEffect(() => {
    loadAllUserNetworks();
  }, []);

  // 当搜索条件变化时重新搜索
  useEffect(() => {
    handleSearch();
  }, [pagination.current, pagination.pageSize, statusFilter, networkTypeFilter]);

  return (
    <MainLayout>
      <div className="network-home-container">
        {/* 页面头部 */}
        <PageHeader />

        {/* 用户网络部分 - 合并显示管理的和已加入的网络 */}
        <UserNetworksSection
          managedNetworks={managedNetworks}
          joinedNetworks={joinedNetworks}
          managedLoading={managedLoading}
          joinedLoading={joinedLoading}
          onRefreshManaged={loadManagedNetworks}
          onRefreshJoined={loadJoinedNetworks}
        />

        {/* 公共局域网部分 */}
        <PublicNetworksSection
          networks={publicNetworks}
          isLoading={searchLoading}
          searchKeyword={searchKeyword}
          statusFilter={statusFilter}
          networkTypeFilter={networkTypeFilter} 
          pagination={pagination}
          onSearch={handleSearch}
          onSearchChange={handleSearchChange}
          onStatusFilterChange={handleStatusFilterChange}
          onNetworkTypeFilterChange={handleNetworkTypeFilterChange} 
          onPageChange={handlePageChange}
          onNetworkJoined={handleNetworkJoined}
        />

        {showToast && (
          <Toast 
            message={toastMessage} 
            onClose={() => setShowToast(false)} 
          />
        )}
      </div>
    </MainLayout>
  );
};

export default NetworkHome;